package com.ruoyi.jacfile.minio;

import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * minio下载上传方法
 */
@Service
public class MinIoService {
    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    private MinioClient minioClient;

    public void setMinioClient() throws InvalidPortException, InvalidEndpointException {
        minioClient = new MinioClient(endpoint, accessKey, secretKey);
    }

    public void minioDownload(String bucketName, String fileName, OutputStream os) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException, ErrorResponseException, XmlPullParserException {
        InputStream fis = null;
        try {
            fis = minioClient.getObject(bucketName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            byte[] bytes = new byte[1024];
            int len=fis.read(bytes);
            while (len>0){
                os.write(bytes,0,len);
                os.flush();
                len = fis.read(bytes);
            }
        } catch (IOException e) {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }

    }

    public String minioUpload(MultipartFile file) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow = sdf.format(new Date());

        // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(dateNow);
            if(!isExist) {
                minioClient.makeBucket(dateNow);
            }
        return FileUploadUtils.upload(dateNow, file, minioClient);
    }

    /**
     * 打印PDF前先将被打印PDF上传
     * backetname=PDF/yyyy-MM-dd
     */
    public String minioUploadPdf(String filepath) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException, InvalidExtensionException, InvalidArgumentException {
        String backetName = "pdf";
        // 检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(backetName);
        if(!isExist) {
            minioClient.makeBucket(backetName);
        }
        return FileUploadUtils.minioUploadPdf(backetName, filepath, minioClient);
    }

    /**
     * 删除文件
     * 仅测试用
     */
    public String delete(String bucketName,String name){
        try {
            minioClient.removeObject(bucketName, name);
        } catch (Exception e) {
            return "删除失败"+e.getMessage();
        }
        return "删除成功";
    }


}
